(function(){
    function app() {
        // 获取当前用户信息
        this.getUserInfo = function() {
            var user = this._get('/admin/app/get_user_info.php');
            return typeof user.error == 'undefined' ? user : null;
        }

        // 用户登录
        this.login = function(username, password) {
            var login = this._post('/admin/app/login.php', 
                {username: username, password: password});
            if (login.error) {
                throw login.error;
                return false;
            }
            return this.redirect('/admin/index.php');
        }

        // 用户登出
        this.logout = function() {
            var logout = this._get('/admin/app/logout.php');
            if (logout.error) {
                throw logout.error;
                return false;
            }
            return this.redirect('/admin/login.php');
        }

        this.user = this.getUserInfo() || null;
    }

    app.prototype = {
        _ajax: function(url, submit, method, dataType) {
            var result;
            $.ajax({
                url:        url,
                data:       submit || {},
                type:       method || 'GET',
                dataType:   dataType || 'json',
                async:      false,
                cache:      false,
                complete:   function(xml) {},
                success:    function(str) {
                    result = str
                }
            })
            return result;
            // return typeof result['error'] == 'undefined' ? result : false;
        },
        _get: function(url, submit) {
            return this._ajax(url, submit, 'GET');
        },
        _post: function(url, submit) {
            return this._ajax(url, submit, 'POST');
        },
        redirect: function(url) {
            window.location.href = url;
        },
        setCookie: function(name,value) {
            var Days = 30; //此 cookie 将被保存 30 天
            var exp  = new Date();    //new Date("December 31, 9998");
            exp.setTime(exp.getTime() + Days*24*60*60*1000);
            document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
        },
        getCookie: function(name) {
            var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
             if(arr != null) return unescape(arr[2]); return null;

        },
        delCookie: function(name) {
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval=this.getCookie(name);
            if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
        }
    }

    window.app = new app();

})();
